import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Modal, Rate, Tabs, Spin } from 'antd';
import { toJS } from 'mobx';
import { WeaTableNew, WeaSwitch } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { WeaRightMenu, WeaTop, WeaTab, WeaErrorPage, WeaTools, WeaNewScroll, WeaSelect, WeaTag } from 'ecCom';
import WeaRightLeftLayout from './comp/weaCrmRightLeft';
import WeaCrmTab from './comp/weaCrmTab';
import WeaDropdown from './comp/weaCrmDropdown';
import { Condition } from './list/listCondition';

const ButtonGroup = Button.Group;
const TabPane = Tabs.TabPane;
import SetTagModal from './public/SetTagModal';
import ViewContactLog from './public/ViewContactLog';
import ViewContacter from './public/ViewContacter';
import CardManage from './card/cardManage';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

@inject('sellChanceStore')
@observer
class SellChanceMain extends React.Component {
  constructor(props) {
    super(props);
    this.setState = {
    };
  }

  componentDidMount() {
    const { sellChanceStore } = this.props;
    const { initDatas, sellChanceTabs, sellChanceStatusAndHrm, doSearch, getSellChanceTagsList, getContactLogs, getRemindCount } = sellChanceStore;
    initDatas(); // 初始化高级搜索
    sellChanceTabs(); // tab栏
    sellChanceStatusAndHrm(); // 状态，人员
    doSearch({haveContacts:false}); // 列表
    getSellChanceTagsList({ type: 'sellchance' }); // 自定义标签
    //getContactLogs();
    getRemindCount();
  }

  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    // 点击菜单路由刷新组件
    if (keyOld !== keyNew) {
      const { sellChanceStore } = nextProps;
      const { initDatas, sellChanceTabs, sellChanceStatusAndHrm, doSearch, getSellChanceTagsList, getContactLogs, getRemindCount, resetTable } = sellChanceStore;
      sellChanceStore.clearStatus();
      initDatas(); // 初始化高级搜索
      sellChanceTabs(); // tab栏
      sellChanceStatusAndHrm(); // 状态，人员
      doSearch({haveContacts:false}); // 列表
      getSellChanceTagsList({ type: 'sellchance' }); // 自定义标签
      //getContactLogs();
      getRemindCount();
      resetTable();
    }
  }
    createHeight = () => {
      const contentH = jQuery('.wea-new-top-req-content').height() - 1;
      return contentH;
    }
    componentWillUnmount() {
      const { sellChanceStore } = this.props;
      sellChanceStore.clearStatus();
    }
    render() {
      const { sellChanceStore, location } = this.props;
      let { title, loading, remindCount, tabDatas, searchBaseParams, showRight, dateSelect, rightTabData, rightTabKey, selectValue, cardloading, tagDatas, contactLogs, contactLogsTotal, contacterCard, contacterCardTotal, leaveMessage, sellChanceCard, rightInfos, cardManageStore } = sellChanceStore;
      title = getLabel(82545, '商机管理');
      rightTabData = [{ title: getLabel(6082, '客户联系'), key: '1' }, { title: getLabel(572, '联系人'), key: '2' }];
      const tabs = [];
      toJS(tabDatas).map((item) => {
        const { key } = item;
        if (key == 'my' || key == 'all' || key == 'attention' || key == 'expire') {
          tabs.push(item);
        } else {
          const { key, labelOrder, labelType, id, title, textColor, isUsed, labelColor } = item;
          const tagitem = {};
          tagitem.key = key;
          tagitem.title = <WeaTag ecId={`${this && this.props && this.props.ecId || ''}_WeaTag@u9vzql@${key}`} color={labelColor} >{title}</WeaTag>;
          tagitem.titleText = title;
          tabs.push(tagitem);
        }
      });
      return (
        <div>
          <WeaRightMenu
            ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@c9oo89`}
            datas={this.getRightMenu()}
            onClick={this.onRightMenuClick.bind(this)}
            collectParams={{
              favname: title,
              favouritetype: 4,
              importantlevel: 1,
              objid: -1,
            }}
          >
            <WeaTop
              ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@yddkr2`}
              title={title}
              loading={loading}
              icon={<i className="icon-coms-crm" />}
              iconBgcolor="#96358a"
              buttons={[]}
              buttonSpace={10}
              showDropIcon
              dropMenuDatas={this.getRightMenu()}
              onDropMenuClick={this.onRightMenuClick.bind(this)}
              buttons={this.getButtons(this.props.ecId || '')}
            >
              <WeaTab
                ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@b9ww2l`}
                selectedKey={searchBaseParams.labelid}
                keyParam="key" // 主键
                onChange={this.changeData.bind(this)}
                datas={tabs}
              />
              <WeaRightLeftLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaRightLeftLayout@p9nuxp`} type={10} defaultShowLeft={false} onClick={(v) => { sellChanceStore.showRightChange(v); }} leftCom={this.getCustomerTable()} >
                {
                  !showRight &&
                  <div className="crm-right-tab">
                    <div className="sellchancemain-right-top">
                      <WeaSelect
                        ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@aos2mu`}
                        value={dateSelect.datatype}
                        options={[{ key: '1', selected: true, showname: getLabel(83223, '近一月') },
                          { key: '2', selected: false, showname: getLabel(83224, '近三月') },
                          { key: '3', selected: false, showname: getLabel(84343, '近半年') },
                          { key: '4', selected: false, showname: getLabel(83225, '近一年') },
                          { key: '5', selected: false, showname: getLabel(332, '全部') }]}
                        onChange={this.dateSelectChange.bind(this)}
                      />
                    </div>
                    <WeaTab
                      ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@j9fr1z`}
                      selectedKey={rightTabKey}
                      datas={toJS(rightTabData)}
                      keyParam="key"
                      onChange={this.changeRightTab.bind(this)}
                    />

                    {
                      rightTabKey == '1' &&
                      <div className="contact-logs-container">
                        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@ew6cxj`} spinning={cardloading} >
                          <ViewContactLog ecId={`${this && this.props && this.props.ecId || ''}_ViewContactLog@7wozxe`} data={toJS(contactLogs)} total={contactLogsTotal} pageChange={(num) => { sellChanceStore.getContactLogs({ pageNum: num }); }} />
                        </Spin>
                      </div>
                    }
                    {
                      rightTabKey == '2' &&
                      <div className="contact-logs-container">
                        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@4aaiyy`} spinning={cardloading} >
                          <ViewContacter ecId={`${this && this.props && this.props.ecId || ''}_ViewContacter@vpy7f7`} data={toJS(contacterCard)} total={contacterCardTotal} pageChange={(num) => { sellChanceStore.getContacterCard({ pageNum: num }); }} />
                        </Spin>
                      </div>
                    }
                  </div>
                }
                {
                  showRight &&
                  <CardManage
                    ecId={`${this && this.props && this.props.ecId || ''}_CardManage@ut2izj`}
                    contentStore={cardManageStore}
                    paramsData={{ from: 'sellchance', fromType: 'sellchance', sellchanceId: rightInfos.sellchanceId, customerId: rightInfos.customerId, ...searchBaseParams }}
                    rightInfos={toJS(rightInfos)}
                    type="sellchance"
                  />
                }
              </WeaRightLeftLayout>
            </WeaTop>

          </WeaRightMenu>
          <SetTagModal ecId={`${this && this.props && this.props.ecId || ''}_SetTagModal@vd0tp4`} ref="setTagModal" data={toJS(tagDatas)} contentStore={sellChanceStore} type={'sellchance'} />
        </div>
      );
    }
    changeData = (key) => {
      const { doSearch, conditionTop, istorefresh, updateParams, getContactLogs } = this.props.sellChanceStore;
      updateParams();
      doSearch({ labelid: key });
      // getContactLogs({labelid:key});
    }
    getCustomerTable() {
      const { sellChanceStore } = this.props;
      const { tableStore, reLoad, doSearch, setShowSearchAd, showSearchAd, appendFormFields, form, searchsBaseKey } = sellChanceStore;
      const formParams = form.getFormParams();
      return (
        <div id="crm-tab-dropdown">
          <WeaCrmTab
            ecId={`${this && this.props && this.props.ecId || ''}_WeaCrmTab@qu93qy`}
            buttonsAd={this.getTabButtonsAd(this.props.ecId || '')}
            searchType={['base', 'advanced']}
            searchsBaseValue={formParams[searchsBaseKey]}
            setShowSearchAd={(bool) => { setShowSearchAd(bool); }}
            hideSearchAd={() => setShowSearchAd(false)}
            searchsAd={<div className="crm-mine-query-condition"><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@w72vg8`} listStore={sellChanceStore} form={form} onEnterSearch={this.onEnterSearch} /></div>}
            showSearchAd={showSearchAd}
            selectGroups={this.getSelectGroups()}
            onSearch={(v) => { doSearch({ [searchsBaseKey]: v }); }}
            onSearchChange={(v) => {
              if (form.has(searchsBaseKey)) {
                form.updateFields({ [searchsBaseKey]: { value: v } }, false);
              }
            }}
            hasDropMenu
          />
          <WeaTable
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@bh43w3`}
            comsWeaTableStore={tableStore}
            hasOrder
            needScroll
            register_table={reLoad}
            getColumns={c => this.reRenderColumns(c)}
            needRowClick
            tableWidth={this.getTableWidth.bind(this)}
            onRowClick={this.onClickRow}
          />
        </div>
      );
    }

    // 选中行
    onClickRow = (record) => {
      this.viewSellChanceDetail(record.randomFieldId);
    }

    reRenderColumns(columns) {
      const { sellChanceStore } = this.props;
      const that = this;
      columns.forEach((c) => {
        if (c.dataIndex == 'subject') {
          c.render = function (text, record) {
            return <div><span dangerouslySetInnerHTML={{ __html: record.subjectspan }} /></div>;
          };
        } else if (c.dataIndex == 'important') {
          c.render = function (text, record) {
            return <div><span><Rate ecId={`${this && this.props && this.props.ecId || ''}_Rate@sz82nn`} count={1} value={text} onChange={(text) => { that.focusOnClick(record.important, record.randomFieldId); }} /></span></div>;
          };
        } else {
          c.render = function (text, record) {
            const valueSpan = record[`${c.dataIndex}span`] !== undefined ? record[`${c.dataIndex}span`] : record[c.dataIndex];
            return <div><span dangerouslySetInnerHTML={{ __html: valueSpan }} /></div>;
          };
        }
      });
      return columns;
    }
    focusOnClick = (num, id) => { // 点击星星
      let flag = 1;
      if (num == '1') { flag = 0; }
      this.markTagsTo(flag, id);
    }
    markTagsTo(i, key) { // 重要  取消重要
      const { isMarkToImportant, doSearch } = this.props.sellChanceStore;
      isMarkToImportant({ relatedIds: key, important: i, type: 'sellchance' });
    }

    getButtons(ecId) {
      const { remindCount, canCreate } = this.props.sellChanceStore;
      let c = 0;
      if (remindCount instanceof Object) {
        c = remindCount.remindCount;
      }
      const btnArr = [];
      canCreate && btnArr.push(<Button ecId={`${ecId}_Button@570ncz@sellchanceAdd`} type="primary" onClick={() => openFullWindowHaveBarForCrm('/main/crm/sellChanceAdd')}>
        <i className="icon-coms-Business-opportunity" /> {getLabel(82, '新建')}
      </Button>);
      btnArr.push(<Button ecId={`${ecId}_Button@knru1b@remind`} type="primary" onClick={() => openFullWindowHaveBarForCrm('/main/crm/contact?tabtype=remind')}>
        <i className="icon-coms-contact" /> {getLabel(16403, '联系提醒')}{`(${c})`}
      </Button>);
      return btnArr;
    }
    getRightMenu() {
      const btns = [];
      // btns.push({
      // 	icon: <i className='icon-coms-Collection'/>,
      // 	content:getLabel(28111,'收藏')
      // });
      // btns.push({
      //     icon: <i className='icon-coms-help'/>,
      //     content:getLabel(275,'帮助'),
      // })
      return btns;
    }
    onRightMenuClick(key) {
      const { actions, comsWeaTable, dataKey } = this.props;
      if (key == '0') {
      }
      if (key == '1') {
      }
    }
    getTabButtonsAd(ecId) {
      const { doSearch, setShowSearchAd, clearFormFields } = this.props.sellChanceStore;
      return [
        (<Button ecId={`${ecId}_Button@7fac68@search`} type="primary" onClick={() => { doSearch(); setShowSearchAd(false); }}>{getLabel(197, '搜索')}</Button>),
        (<Button ecId={`${ecId}_Button@6pnvk2@reset`} type="ghost" onClick={() => { clearFormFields({}); }}>{getLabel(2022, '重置')}</Button>),
        (<Button ecId={`${ecId}_Button@tq4hvx@cancel`} type="ghost" onClick={() => { setShowSearchAd(false); }}>{getLabel(201, '取消')}</Button>),
      ];
    }
    getSelectGroups() {
      const { sellChanceStatus, hrmList, viewTypeList, istorefresh, tagDatas, tableStore, searchBaseParams, quickList, contactOptions, quickConditions } = this.props.sellChanceStore;

      const { selectedRowKeys } = tableStore;
      const sellChanceStatus1 = toJS(sellChanceStatus);
      const hrmList1 = toJS(hrmList);
      const that = this;
      const tabs = [];

      tabs.push(
        <TabPane
          ecId={`${this && this.props && this.props.ecId || ''}_TabPane@hkrmuu@tp`}
          tab={
            <WeaDropdown
              ecId={`${this && this.props && this.props.ecId || ''}_WeaDropdown@p6zgka@dropdown`}
              defaultValue={getLabel(176, '标签')}
              type="tag"
              datas={toJS(tagDatas)}
              selectKeys={`${toJS(selectedRowKeys)}`}
              markTagsTo={that.markTagsTo.bind(that)}
              markToCustomTag={that.markToCustomTag.bind(that)}
              setting={that.setting.bind(that)}
              layout="crm-tab-dropdown"
            />
          }
          key="8"
        />,
      );

      if (viewTypeList.length > 0 && hrmList1.length > 0 && searchBaseParams.labelid == 'my') {
        const k1 = 'creater_str';
        tabs.push(
          <TabPane
            ecId={`${this && this.props && this.props.ecId || ''}_TabPane@scnb7t@tp`}
            tab={
              <WeaDropdown
                ecId={`${this && this.props && this.props.ecId || ''}_WeaDropdown@h8pc7j@dropdown`}
                value={quickConditions[k1]}
                valueSpan={quickConditions[`${k1}span`]}
                keyValue={k1}
                defaultValue={hrmList1[0].name}
                type="tree"
                datas={hrmList1}
                hrmListChange={that.hrmListChange.bind(that)}
                onChange={(obj) => { this.selectChange(obj, { quickSign: k1, quickSearch: k1 }); }}
                layout="crm-tab-dropdown"
              />
            }
            key="1"
          />,
        );
        const k2 = 'containsSub';
        tabs.push(
          <TabPane
            ecId={`${this && this.props && this.props.ecId || ''}_TabPane@4whtp7@tp`}
            tab={
              <WeaDropdown
                ecId={`${this && this.props && this.props.ecId || ''}_WeaDropdown@a8gj27@dropdown`}
                value={quickConditions[k2]}
                valueSpan={quickConditions[`${k2}span`]}
                keyValue={k2}
                defaultValue={toJS(viewTypeList)[0].name}
                type="select"
                datas={toJS(viewTypeList)}
                onChange={(obj) => { this.selectChange(obj, { quickSign: k2, quickSearch: k2 }); }}
                layout="crm-tab-dropdown"
              />
            }
            key="2"
          />,
        );
      }
      const k3 = 'contactTime_str';
      tabs.push(
        <TabPane
          ecId={`${this && this.props && this.props.ecId || ''}_TabPane@mwucln@tp`}
          tab={
            <WeaDropdown
              ecId={`${this && this.props && this.props.ecId || ''}_WeaDropdown@1tibte@dropdown`}
              layout="crm-tab-dropdown"
              value={quickConditions[k3]}
              valueSpan={quickConditions[`${k3}span`]}
              keyValue={k3}
              defaultValue={getLabel(16405, '联系情况')}
              type="select"
              datas={toJS(contactOptions)}
              onChange={(obj) => { this.selectChange(obj, { quickSign: k3, quickSearch: k3 }); }}
            />
          }
          key="7"
        />,
      );

      for (const quickMap of quickList) {
        if (quickMap.quickSign && quickMap.quickSign == 'predate') {
          tabs.push(
            <TabPane
              ecId={`${this && this.props && this.props.ecId || ''}_TabPane@aopldd@tp`}
              tab={
                <WeaDropdown
                  ecId={`${this && this.props && this.props.ecId || ''}_WeaDropdown@0bgcht@dropdown`}
                  layout="crm-tab-dropdown"
                  value={quickConditions[quickMap.quickSearch]}
                  valueSpan={quickConditions[`${quickMap.quickSearch}span`]}
                  keyValue={quickMap.quickSearch}
                  defaultValue={quickMap.quickName}
                  type="select"
                  datas={quickMap.quickOptions}
                  onChange={(obj) => { this.selectChange(obj, quickMap); }}
                />
              }
              key="4"
            />,
          );
          continue;
        } else if (quickMap.quickSign && quickMap.quickSign == 'preyield') {
          tabs.push(
            <TabPane
              ecId={`${this && this.props && this.props.ecId || ''}_TabPane@9xxywi@tp`}
              tab={
                <WeaDropdown
                  ecId={`${this && this.props && this.props.ecId || ''}_WeaDropdown@5iqev9@dropdown`}
                  layout="crm-tab-dropdown"
                  value={quickConditions[`${quickMap.quickSearch}_1`]}
                  valueSpan={quickConditions[`${quickMap.quickSearch}span`]}
                  keyValue={quickMap.quickSearch}
                  defaultValue={quickMap.quickName}
                  type="select"
                  datas={quickMap.quickOptions}
                  onChange={(obj) => { this.selectChange(obj, quickMap); }}
                />
              }
              key="5"
            />,
          );
        } else if (quickMap.quickSign && quickMap.quickSign == 'probability') {
          tabs.push(
            <TabPane
              ecId={`${this && this.props && this.props.ecId || ''}_TabPane@53fp7p@tp`}
              tab={
                <WeaDropdown
                  ecId={`${this && this.props && this.props.ecId || ''}_WeaDropdown@kmmpvd@dropdown`}
                  layout="crm-tab-dropdown"
                  value={quickConditions[quickMap.quickSearch]}
                  valueSpan={quickConditions[`${quickMap.quickSearch}span`]}
                  keyValue={quickMap.quickSearch}
                  defaultValue={quickMap.quickName}
                  type="select"
                  datas={quickMap.quickOptions}
                  onChange={(obj) => { this.selectChange(obj, quickMap); }}
                />
              }
              key="6"
            />,
          );
        } else {
          tabs.push(
            <TabPane
              ecId={`${this && this.props && this.props.ecId || ''}_TabPane@6lmytf@tp`}
              tab={
                <WeaDropdown
                  ecId={`${this && this.props && this.props.ecId || ''}_WeaDropdown@mhnlw8@dropdown`}
                  layout="crm-tab-dropdown"
                  value={quickConditions[quickMap.quickSearch]}
                  valueSpan={quickConditions[`${quickMap.quickSearch}span`]}
                  keyValue={quickMap.quickSearch}
                  defaultValue={quickMap.quickName}
                  type={quickMap.multiple ? 'selectMultiple' : 'select'}
                  datas={quickMap.quickOptions}
                  onChange={(obj) => { this.selectChange(obj, quickMap); }}
                />
              }
              key={quickMap.quickKey}
            />,
          );
        }
      }
      return <Tabs ecId={`${this && this.props && this.props.ecId || ''}_Tabs@u0qkf2`} defaultActiveKey="" key={istorefresh}>{tabs}</Tabs>;
    }
    hrmListChange = (arr) => {
      const { saveHrmList } = this.props.sellChanceStore;
      saveHrmList(arr);
    }
    selectChange(obj, quickMap) {
      const { doSearchQuick, getContactLogs, setRightTabKey, saveSelectValue } = this.props.sellChanceStore;
      doSearchQuick(obj, quickMap);
      getContactLogs({ datatype: '1' });
      saveSelectValue('1');
      setRightTabKey('1', false);
    }
    markToCustomTag(lablestr, selectkey, type) { // 应用  取消某标签
      const { markToCustomTagType } = this.props.sellChanceStore;
      markToCustomTagType({ relatedIds: selectkey, labelIds: lablestr, operationType: type, type: 'sellchance' });
    }
    setting() {
      this.refs.setTagModal.visible = true;
    }

    viewSellChanceDetail = (id) => {
      const { getSellChanceDetail } = this.props.sellChanceStore;
      getSellChanceDetail(id);
    }
    dateSelectChange(val) {
      const { getContactLogs, getContacterCard, getLeaveMessage, getSellchanceCard, rightTabKey } = this.props.sellChanceStore;
      if (rightTabKey == '1') { getContactLogs({ datatype: val }); }
      if (rightTabKey == '2') { getContacterCard({ datatype: val }); }
    }
    changeRightTab(key) {
      const { setRightTabKey } = this.props.sellChanceStore;
      setRightTabKey(key);
    }

    onEnterSearch=() => {
      const { sellChanceStore } = this.props;
      sellChanceStore.doSearch();
      sellChanceStore.setShowSearchAd(false);
    }

    getTableWidth = (columns) => {
      const showLength = columns.filter(col => col.display == 'true').length;
      return 120 * showLength;// 也支持返回固定值，如果小于100%,不会生效。
    }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@78upas`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' },
)(SellChanceMain);
